package rpc;

//rpc客户端，负责发送请求和接受响应


import com.rabbitmq.client.*;
import contants.Constants;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

public class RpcClient {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.建立连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.HOST);//主机ip
        factory.setPort(Constants.PORT);//端口号
        factory.setUsername(Constants.USER_NAME);//用户名
        factory.setPassword(Constants.PASSWORD);//用户密码
        factory.setVirtualHost(Constants.VIRTUAL_HOST);//虚拟主机
        Connection connection = factory.newConnection();
        //2.开启信道声明对应
        Channel channel = connection.createChannel();
        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE, true, false, false, null);
        channel.queueDeclare(Constants.RPC_RESPONSE_QUEUE, true, false, false, null);
        //3.发送请求（放入请求队列）
        //3.1.构造消息体
        String msg = "我是一条rpc请求消息";
        //3.2.消息唯一标识符（序号）
        String correlationID = UUID.randomUUID().toString();
        //3.3.设置消息的属性
        AMQP.BasicProperties props = new AMQP.BasicProperties()
                                    .builder()
                                    .correlationId(correlationID)//消息标识符
                                    .replyTo(Constants.RPC_RESPONSE_QUEUE)//响应放回的队列
                                    .build();
        channel.basicPublish("",Constants.RPC_REQUEST_QUEUE,props,msg.getBytes());
        //4.接收响应（从响应队列获取）
        final BlockingQueue<String> response = new ArrayBlockingQueue<>(1);
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body);
                System.out.println("接收到回调消息"+msg);
                //放入阻塞队列中
                if(correlationID.equals(properties.getCorrelationId())) {
                    response.offer(msg);
                }
            }
        };
        channel.basicConsume(Constants.RPC_RESPONSE_QUEUE,true,consumer);
        //5.从阻塞队列中取出响应
        String result = response.take();
        System.out.println("接收到的响应:[]"+result);
    }
}
